package com.cb.domain.dao.system.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.cb.core.Constants;
import com.cb.core.dao.hibernate.GenericDAOHibernate;
import com.cb.core.spring.ex.security.RoleMapping;
import com.cb.core.webapp.paging.PagingBean;
import com.cb.domain.dao.system.AppRoleDAO;
import com.cb.domain.model.system.AppResource;
import com.cb.domain.model.system.AppRole;
@Repository
public class AppRoleDAOImpl extends GenericDAOHibernate<AppRole, Long> implements AppRoleDAO {
	public AppRoleDAOImpl() {
		super(AppRole.class);
	}
	
	/**
	 * {@inheritDoc}
	 */
	public List<AppRole> getByVo(AppRole vo, PagingBean pb) {
		List<Object>paramList=new ArrayList<Object>();
		String hql="from AppRole vo where 1=1";
		
		List <AppRole>list=this.find(hql, paramList.toArray(), pb);
		return list;
	}
	
	public List getUnselectedRoles(Long userId){
		String hql="from AppRole ar where ar.status=? and ar.roleId not in (select rs.roleId from UserCompany au join au.roles rs where au.companyUserId=?)";
		return find(hql, new Object[]{Constants.STATUS_ACTIVE,userId});
	}
	
	/**
	 * {@inheritDoc}
	 */
	public RoleMapping[] constructRoleMappings() {
		
			// 取得所有的角色
			Session session=getSession();
			try{
				String hql="from AppRole where status=?";
				Query query=getSession().createQuery(hql);
				query.setShort(0, Constants.STATUS_ACTIVE);
				List allRoles = query.list();
	
				RoleMapping[] roleMappings = new RoleMapping[allRoles.size()];
	
				for (int i = 0; i < allRoles.size(); i++) {
	
					roleMappings[i] = new RoleMapping();
					
					AppRole appRole = (AppRole) allRoles.get(i);
	
					roleMappings[i].setRoleName(appRole.getRoleName());
	
					Set resourceSet=appRole.getResources();
	
					String[] urlPatterns = new String[resourceSet.size()];
					
					int j = 0;
					
					Iterator it = resourceSet.iterator();
	
					while (it.hasNext()) {
						AppResource appResource=(AppResource)it.next();
						urlPatterns[j++] = appResource.getResourceUrl();
					}
					roleMappings[i].setUrlPatterns(urlPatterns);
					
				}
				return roleMappings;
			}finally{
				releaseSession(session);
			}
	}
}

